package dao

import (
	"context"
	"database/sql"
	"dogapm"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type userDao struct {
	ID        uint           `json:"id" gorm:"id;primarykey"`
	CreatedAt sql.NullTime   `json:"createdAt" gorm:"created_at"`
	UpdatedAt sql.NullTime   `json:"updatedAt" gorm:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Name      string         `json:"name" gorm:"name"`
}

func (u *userDao) TableName() string {
	return "t_user"
}

var UserDao = &userDao{}

func (u *userDao) Get(ctx context.Context, uid int64) (userDao, bool) {
	userCache, err := dogapm.Infra.RDB.Get(ctx, fmt.Sprintf("%s:%s:%d", "usersvc", "uinfo", uid)).Result()
	if len(userCache) != 0 {
		err = json.Unmarshal([]byte(userCache), u)
		if err == nil {
			return *u, true
		}
	}

	rows := dogapm.Infra.MySqlDB.Model(u).First(u, "id = ?", uid).RowsAffected

	if rows == 0 {
		dogapm.Logger.Info(ctx, "GetUserInfo", map[string]interface{}{
			"msg": "user not found",
			"uid": uid,
		})
		return userDao{}, false
	}
	cacheUserStr, err := json.Marshal(*u)
	if err == nil {
		dogapm.Infra.RDB.Set(ctx, fmt.Sprintf("%s:%s:%d", "usersvc", "uinfo", uid), cacheUserStr, 10*time.Minute)
	}
	return *u, true
}
